package com.yinwq.shorturl.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: yinwenqiang@qccr.com
 * @date: Created in 2019/11/28 15:06
 */
public class Test {
    public static void main(String[] args) {
        String json = "{\"database\":\"test_maxwell\",\"table\":\"user_info\",\"type\":\"update\",\"ts\":1533857219,\"xid\":10595,\"commit\":true,\"data\":{\"user_id\":3,\"name\":\"name3\",\"age\":23},\"old\":{\"age\":30}}";
        JSONObject jsonObject = JSON.parseObject(json);
        Map<String, Object> data = new HashMap<>();
        String eventType = (String) jsonObject.get("type");
        String schemaName = (String) jsonObject.get("database");
        String tableName = (String) jsonObject.get("table");
        // otter为大写
        if (StringUtils.isNotEmpty(eventType)) {
            data.put("eventType", eventType.toUpperCase());
        }
        data.put("schemaName", schemaName);
        data.put("tableName", tableName);
        JSONObject dataObj = (JSONObject) jsonObject.get("data");
        if (dataObj != null && CollectionUtils.isNotEmpty(dataObj.entrySet())) {
            Map<String, Object> rawData = new HashMap<>(dataObj.entrySet().size());
            data.put("rawData", rawData);
            for (Map.Entry<String, Object> entry : dataObj.entrySet()) {
                rawData.put(StringUtil.underline2Camel(entry.getKey()), entry.getValue() == null ? null : entry.getValue() + "");
            }
        }
        JSONObject oldObj = (JSONObject) jsonObject.get("old");
        if (oldObj != null && CollectionUtils.isNotEmpty(oldObj.entrySet())) {
            Map<String, Object> oldData = new HashMap<>(oldObj.entrySet().size());
            data.put("oldData", oldData);
            for (Map.Entry<String, Object> entry : oldObj.entrySet()) {
                oldData.put(StringUtil.underline2Camel(entry.getKey()), entry.getValue() == null ? null : entry.getValue() + "");
            }
        }
        System.err.println(data);
    }


}
